﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using ProxyHero.Entity;
using ProxyHero.HttpUility;

namespace ProxyHero.Common
{
    public class IpHelper
    {
        public IpHelper()
        { }

        private string m_Location = "", m_IpAddress = "", m_Response = "", m_ProxyType = "", m_proxyAddress = "";

        /// <summary>
        /// 代理匿名类型
        /// </summary>
        public string ProxyType
        {
            get
            {
                try
                {
                    Regex regex = new Regex(@"(?<IP>(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))\:(?<Port>\d{1,5})");
                    MatchCollection matchs = regex.Matches(m_proxyAddress);
                    if (matchs.Count == 1)
                    {
                        ProxyEntity pe = new ProxyEntity();
                        pe.Ip = matchs[0].Groups["IP"].Value;
                        pe.Port = int.Parse(matchs[0].Groups["Port"].Value);

                        TestEntity te = new TestEntity();
                        te.TestUrl = "http://www.stilllistener.com/checkpoint1/test1/";
                        te.TestWebEncoding = "iso-8859-1";
                        te.TestWebTitle = "Test 1";

                        string localIp = NetHelper.LocalPublicIp;

                        string REMOTE_ADDR = "", HTTP_VIA = "", HTTP_X_FORWARDED_FOR = "";

                        string html = (string)HttpHelper.TestProxy(pe, te)[2];
                        html = StringHelper.GetMidString(html, "<TABLE>", "</TABLE>");

                        REMOTE_ADDR = StringHelper.GetMidString(html, "REMOTE_ADDR</TD>\n<TD>", "</TD>");
                        HTTP_VIA = StringHelper.GetMidString(html, "HTTP_VIA</TD>\n<TD>", "</TD>");
                        if (!HTTP_VIA.Contains("none"))
                        {
                            HTTP_VIA = StringHelper.GetMidString(StringHelper.GetMidString(html, "HTTP_VIA</TD>\n<TD>", "</TD>"), "<b>", "</b>");
                        }
                        HTTP_X_FORWARDED_FOR = StringHelper.GetMidString(html, "HTTP_X_FORWARDED_FOR</TD>\n<TD>", "</TD>");

                        if (!HTTP_X_FORWARDED_FOR.Contains("none"))
                        {
                            HTTP_X_FORWARDED_FOR = StringHelper.GetMidString(StringHelper.GetMidString(html, "HTTP_X_FORWARDED_FOR</TD>\n<TD>", "</TD>"), "<b>", "</b>");
                        }

                        string[] peIps = pe.Ip.Split('.');
                        string peIp = peIps[0] + "." + peIps[1];

                        if (REMOTE_ADDR.Contains(localIp) &&
                            HTTP_VIA.Contains("none") &&
                            HTTP_X_FORWARDED_FOR.Contains("none"))
                        {
                            m_ProxyType = "未使用代理";
                        }
                        else if ((REMOTE_ADDR.Contains(pe.Ip) || REMOTE_ADDR.Contains(peIp)) &&
                            HTTP_X_FORWARDED_FOR.Contains(localIp))
                        {
                            m_ProxyType = "透明代理";
                        }
                        else if ((REMOTE_ADDR.Contains(pe.Ip) || REMOTE_ADDR.Contains(peIp)) &&
                            !HTTP_VIA.Contains("none") &&
                            (HTTP_X_FORWARDED_FOR.Contains(pe.Ip) || HTTP_X_FORWARDED_FOR.Contains("none")))
                        {
                            m_ProxyType = "匿名代理";
                        }
                        else if ((REMOTE_ADDR.Contains(pe.Ip) || REMOTE_ADDR.Contains(peIp)) &&
                            !HTTP_VIA.Contains("none") &&
                            (!HTTP_X_FORWARDED_FOR.Contains(localIp) && !HTTP_X_FORWARDED_FOR.Contains(pe.Ip) && !HTTP_X_FORWARDED_FOR.Contains("none")))
                        {
                            m_ProxyType = "欺骗性匿名代理";
                        }
                        else if ((REMOTE_ADDR.Contains(pe.Ip) || REMOTE_ADDR.Contains(peIp)) &&
                            HTTP_VIA.Contains("none") &&
                            HTTP_X_FORWARDED_FOR.Contains("none"))
                        {
                            m_ProxyType = "高匿名代理";
                        }
                        else
                        {
                            if (REMOTE_ADDR != "")
                            {
                                StringBuilder sb = new StringBuilder("本机IP：" + localIp + "；");
                                sb.Append("REMOTE_ADDR：" + REMOTE_ADDR + "；");
                                sb.Append("HTTP_VIA：" + HTTP_VIA + "；");
                                sb.Append("HTTP_X_FORWARDED_FOR：" + HTTP_X_FORWARDED_FOR);
                                m_ProxyType = sb.ToString();
                            }
                            else
                            {
                                m_ProxyType = "HTTP";
                            }
                        }
                    }
                }
                catch
                {
                    m_ProxyType = "HTTP";
                }

                return m_ProxyType;
            }
            set { m_ProxyType = value; }
        }

        /// <summary>
        /// 新建IpLocation实例以获得IP地理位置
        /// </summary>
        /// <param name="ipAddress"></param>
        public IpHelper(string ipAddress)
        {
            m_proxyAddress = ipAddress.Trim();
            m_IpAddress = ipAddress.Trim();

            Regex regex = new Regex(@"(?<IP>(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))");
            MatchCollection matchs = regex.Matches(ipAddress);
            if (matchs.Count == 1)
            {
                ipAddress = matchs[0].Groups["IP"].Value;

                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.GetEncoding("GB2312");

                string url = "http://www.ip138.com/ips.asp";
                string post = "ip=" + ipAddress + "&action=2";
                client.Headers.Set("Content-Type", "application/x-www-form-urlencoded");
                client.Proxy = null;
                string response = client.UploadString(url, post);
                m_Response = response;

                string p = @"<li>参考数据二：(?<location>[^<>]+?)</li>";

                Match match = Regex.Match(response, p);
                m_Location = match.Groups["location"].Value.Trim();
            }
        }

        /// <summary>
        /// 返回Ip地址的地理位置名称
        /// </summary>
        public string Location
        {
            get
            {
                return m_Location;
            }
        }

        public string IpAddress
        {
            get
            {
                return m_IpAddress;
            }
        }

        /// <summary>
        /// 返回网络反馈原始数据
        /// </summary>
        public string Response
        {
            get
            {
                return m_Response;
            }
        }
    }
}
